<?php

require_once dirname(__FILE__) . '/vendors/min/Minify/JS/ClosureCompiler.php';
require_once dirname(__FILE__) . '/vendors/min/Minify/YUI/CssCompressor.php';

class Minify extends CApplicationComponent
{

    public function init()
    {
	parent::init();
    }

    public function processJs($sourceList)
    {
	if (empty($sourceList)) {
	    return;
	}

	foreach ($sourceList as $filename => $fileList) {
	    if (!is_string($filename)) {
		continue;
	    }
	    if (file_exists($_SERVER['DOCUMENT_ROOT'] . $filename)) {
		Yii::app()->clientScript->registerScriptFile($filename, CClientScript::POS_END);
		continue;
	    }
	    $file = '';
	    if (is_array($fileList) && !empty($fileList)) {
		foreach ($fileList as $source) {
		    if (file_exists($_SERVER['DOCUMENT_ROOT'] . $source)) {
			$file .= Minify_JS_ClosureCompiler::minify(file_get_contents($_SERVER['DOCUMENT_ROOT'] . $source));
		    }
		}
	    }
	    if (!empty($file)) {
		if (!file_put_contents($_SERVER['DOCUMENT_ROOT'] . $filename, $file)) {
		    throw new Exception('File ' . $filename . ' is not writable');
		}
		Yii::app()->clientScript->registerScriptFile($filename, CClientScript::POS_END);
	    }
	}
    }

    public function processCss($sourceList, $media = 'screen')
    {
	if (empty($sourceList)) {
	    return;
	}
	$cssCompressor = new Minify_YUI_CssCompressor();
	foreach ($sourceList as $filename => $fileList) {
	    if (!is_string($filename)) {
		continue;
	    }
	    if (file_exists($_SERVER['DOCUMENT_ROOT'] . $filename)) {
		Yii::app()->clientScript->registerCssFile($filename, $media);
		continue;
	    }
	    $file = '';
	    if (is_array($fileList) && !empty($fileList)) {
		foreach ($fileList as $source) {
		    if (file_exists($_SERVER['DOCUMENT_ROOT'] . $source)) {
			$file .= $cssCompressor->compress(file_get_contents($_SERVER['DOCUMENT_ROOT'] . $source));
		    }
		}
	    }
	    if (!empty($file)) {
		if (!file_put_contents($_SERVER['DOCUMENT_ROOT'] . $filename, $file)) {
		    throw new Exception('File ' . $filename . ' is not writable');
		}
		Yii::app()->clientScript->registerCssFile($filename, $media);
	    }
	}
    }

}
